package com.dz.risk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dz.risk.common.ExcelUtils;
import com.dz.risk.common.GeneralUtils;
import com.dz.risk.common.ResponseVO;
import com.dz.risk.common.SysConstant;
import com.dz.risk.common.exception.RRException;
import com.dz.risk.dao.RiskFactorDao;
import com.dz.risk.pojo.model.FormulaModel;
import com.dz.risk.pojo.domain.RiskFactorEntity;
import com.dz.risk.pojo.domain.RiskFactorValueEntity;
import com.dz.risk.service.RiskFactorService;
import com.dz.risk.service.RiskFactorValueService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class RiskFactorServiceImpl extends ServiceImpl<RiskFactorDao, RiskFactorEntity> implements RiskFactorService {


    @Autowired
    RiskFactorDao riskFactorDao;

    @Autowired
    RiskFactorValueService factorValueService;

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = RuntimeException.class)
    public ResponseVO readExcelRiskFactor(Workbook wb) throws RRException {
        //拿到对应的表
        try {
            Sheet sheet1 = wb.getSheetAt(0);
            //拿到这表的总行数
            int lastRowNum = sheet1.getLastRowNum();
            if (lastRowNum == 0) {
                return ResponseVO.fail("Please fill in data before importing");
            }
            List<RiskFactorEntity> list = new ArrayList<>();
            List<RiskFactorValueEntity> listVal = new ArrayList<>();
            return getSheetValue(list, listVal, lastRowNum, sheet1);
        } catch (RRException e) {
            log.error("===>" + e.getCause());
            throw new RRException("readExcelRiskFactor is error", e.getCause());
        }
    }


    @Override
    public void add(RiskFactorEntity factorEntity) throws RRException {
        factorEntity.setId(GeneralUtils.randomUUID(SysConstant.EIGHT));
        this.save(factorEntity);
    }

    @Override
    public void updateRiskContent(RiskFactorEntity factorEntity) throws RRException {
        this.updateById(factorEntity);
    }

    @Override
    public void deleteById(String id) throws RRException {
        riskFactorDao.deleteById(id);
    }

    @Override
    public IPage<RiskFactorEntity> listByParams(Integer pageNum, Integer pageSize, String searchName) throws RRException {
        IPage<RiskFactorEntity> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        QueryWrapper<RiskFactorEntity> query = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(searchName)) {
            query.and(wrapper -> wrapper.
                    like("risk_content", searchName));
        }
        query.orderByDesc("created_time");
        return riskFactorDao.selectPage(page, query);
    }

    /**
     * 读取excel表格数据
     *
     * @param list
     * @param listVal
     * @param lastRowNum
     * @param sheet1
     */
    public ResponseVO getSheetValue(List<RiskFactorEntity> list, List<RiskFactorValueEntity> listVal, int lastRowNum, Sheet sheet1)
            throws RRException {
        for (int i = 1; i <= lastRowNum; i++) {
            //拿到每一行
            Row row = sheet1.getRow(i);
            Cell code = row.getCell(0);
            Cell content = row.getCell(1);
            if (content == null) {
                return ResponseVO.fail("Risk factors cant null");
            } else {
                // 编码为空  内容不为空
                if (code == null) {
                    {
                        LambdaQueryWrapper<RiskFactorEntity> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(RiskFactorEntity::getRiskContent, content.getStringCellValue());
                        RiskFactorEntity db = riskFactorDao.selectOne(queryWrapper);
                        if (db != null) {
                            return ResponseVO.fail("Risk factors already exist");
                        } else {
                            db = new RiskFactorEntity();
                            db.setRiskContent(content.getStringCellValue());
                            this.save(db);
                        }
                    }
                } else {
                    // 编码和内容都不为空
                    LambdaQueryWrapper<RiskFactorEntity> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(RiskFactorEntity::getRiskContent, content.getStringCellValue());
                    queryWrapper.eq(RiskFactorEntity::getRiskCode, BigInteger.valueOf(Long.parseLong(code.getStringCellValue())));
                    RiskFactorEntity db = riskFactorDao.selectOne(queryWrapper);
                    // 如果编码和内容不同时存在
                    if (db == null) {
                        // 判断编码是否存在
                        LambdaQueryWrapper<RiskFactorEntity> codeWrapper = new LambdaQueryWrapper<>();
                        codeWrapper.eq(RiskFactorEntity::getRiskCode, BigInteger.valueOf(Long.parseLong(code.getStringCellValue())));
                        RiskFactorEntity codeDb = riskFactorDao.selectOne(codeWrapper);
                        LambdaQueryWrapper<RiskFactorEntity> contentWrapper = new LambdaQueryWrapper<>();
                        contentWrapper.eq(RiskFactorEntity::getRiskContent, content.getStringCellValue());
                        RiskFactorEntity contentDb = riskFactorDao.selectOne(contentWrapper);
                        // 编码存在
                        if (codeDb != null) {
                            if (contentDb != null) {
                                return ResponseVO.fail("Risk factors already exist");
                            } else {
                                codeDb.setRiskContent(content.getStringCellValue());
                                this.updateById(codeDb);
                            }
                        } else {
                            // 编码不存在
                            if (contentDb != null) {
                                return ResponseVO.fail("RiskCode cant change");
                            } else {
                                RiskFactorEntity addDb = new RiskFactorEntity();
                                addDb.setRiskContent(content.getStringCellValue());
                                this.save(addDb);
                            }
                        }
                    }
                }
            }
        }
        return ResponseVO.ok();
    }
}